package com.geneqiao.jdbc.pool;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class JDBCDataSource
{

	// 日志
	private static final Logger logger = Logger.getLogger(JDBCDataSource.class);
	private static final String defaultConfig = "jdbc.properties";
	private JDBCPool jdbcPool;

	private JDBCDataSource(String fileName)
	{
		try
		{
			Properties prop = new Properties();
			// 在静态代码块中加载db.properties数据库配置文件
			InputStream in = JDBCDataSource.class.getClassLoader().getResourceAsStream(fileName);
			prop.load(in);
			this.jdbcPool = new JDBCPool(prop);
		}
		catch (Exception e)
		{
			logger.error("初始化配置文件失败", e);
		}
		
	}

	public static JDBCDataSource getInstance(String fileName)
	{
		return new JDBCDataSource(fileName);
	}

	public static JDBCDataSource getInstance()
	{
		return getInstance(defaultConfig);
	}

	public Connection getConnection()
	{
		try
		{
			return jdbcPool.getConnection();
		}
		catch (SQLException | InterruptedException e)
		{
			logger.error("获取数据库链接失败", e);
		}
		return null;
	}

	public void colseConnection(Connection conn)
	{
		try
		{
			jdbcPool.colseConnection(conn);
		}
		catch (SQLException e)
		{
			logger.error("Release connection faild", e);
		}
	}

	public void shutdown()
	{
		jdbcPool.shutdown();
	}
}
